/**
 * Created by aa on 2016/5/26.
 */

var express = require('express');
var crypto = require('crypto');
var router = express.Router();
var User = require('../models/test.js');
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var component = require('../public/javascripts/components/testComponents.jsx');
var mainRender= require('../render/mainRender.jsx');
var detailRender= require('../render/detailRender.jsx');
var fs = require("fs")
var COMMENTS_FILE='../comments.json';
var TEST_DATA='../testData.json';
var url = require('url');
/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express', layout: 'layoutfortest'});
});

router.get('/test', function (req, res, next) {
    res.render('test/testlogin', {title: '测试', layout: 'layoutfortest'});
});

router.get('/home', function (req, res, next) {
   /* var element = React.createFactory(component.Home)();
    var mainHome = ReactDOMServer.renderToString(element);*/
    var mainHome=mainRender;
   /* mainHome.renderFunc(req,res,(reactOutput,initializeStore)=>{
        res.render('react/home', {title: '测试', reactOutput: reactOutput, layout: 'layoutfortest',initializeStore:initializeStore});
    });*/
    mainRender.RenderFunc((main,initializeStore)=>{
        res.render('react/home', {title: '测试', reactOutput:main, layout: 'layoutfortest',initializeStore:initializeStore,index:'index'});
    });
   // res.render('react/home', {title: '测试', reactOutput: mainHome.main, layout: 'layoutfortest',initializeStore:mainHome.initializeStore});
   /* res.render('test/testlogin', {title: '测试', layout: 'layoutfortest'});*/
});

router.get('/detail',function(req,res,next){
    var id=req.query.id;
    var detail=detailRender;
    detail.RenderFunc(id,(main,initializeStore)=>{
        res.render('react/home', {title: '测试', reactOutput:main, layout: 'layoutfortest',initializeStore:initializeStore,index:'detail'});
    });
});

router.post('/test', function (req, res, next) {
    var user = new User({name: req.body.username, password: req.body.password});
    user.getUser(req.body.username, function (user) {
        if (!user) {
            req.flash('error', '用户不存在');
            return res.redirect('/test');
        }
        else {
            var md5 = crypto.createHash('md5');
            var password = md5.update(req.body.password).digest('base64');
            if (password == user.password) {
                req.flash('success', '登录成功');
                return res.redirect('/');
            }
            else {
                req.flash('error', '密码错误');
                return res.redirect('/test');
            }
        }
    })
});

router.get('/api/testdata', function (req, res) {
    fs.readFile(TEST_DATA, function (err, data) {
        if (err) {
            console.error(err);
            process.exit(1);
        }
        res.json(JSON.parse(data));
    });
});

module.exports = router;